/*
* 质量巡检
* */

import 'dart:convert';

import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class QualityInspection extends StatefulWidget {
  @override
  _QualityInspectionState createState() => _QualityInspectionState();
}

class _QualityInspectionState extends State<QualityInspection>
    with TickerProviderStateMixin {
  EasyRefreshController _controller = EasyRefreshController();
  int currentIndex = 0;
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;
  List dataSource = [];
  List statusList = ['全部状态', '待整改', '待复查', '已完结'];
  var selectStatus = '全部状态';
  var selectStatusType = '1|2|3|4';
  @override
  void initState() {
    super.initState();
    // this.getTaskList();
  }

  /*
  * 获取任务列表
  * */
  getTaskList() async {
    var result = await getAllTasks({
      'issueType2': '2',
      'tenantId': GlobalConfig.tenantId,
      'queryFields': json.encode([{
        'columnName': 'issueStatus',
        'dataType': 'String',
        'operator': 'in',
        'queryValue': this.selectStatusType,
      },{"columnName":"projectSectionId","dataType":"String","operator":"equal","queryValue":GlobalConfig.selectFactory.tag}]),
      'page': page,
      'limit': pageSize,
    });
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null && result['results'] != null) {
      if (result['results'].length == 0) {
        _controller.finishLoad(success: true, noMore: true);
      } else {
        dataSource.addAll(result['results']);
        if(dataSource.length==result['totalRecordNum']){
          _controller.finishLoad(success: true, noMore: true);
        }
      }
    }
    setState(() {

    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('质量巡检'),
          actions: [
            GestureDetector(
              onTap: (){
                Pickers.showSinglePicker(context,
                    data: this.statusList,
                    selectData: selectStatus, onConfirm: (p, position) {
                      setState(() {
                        selectStatus = p;
                        page = 1;
                        switch (position){
                          case 0:
                            selectStatusType = "1|2|3|4";
                            break;
                          case 1:
                            selectStatusType = "2";
                            break;
                          case 2:
                            selectStatusType = "3";
                            break;
                          case 3:
                            selectStatusType = "4";
                            break;
                          default:
                            selectStatusType = "1|2|3|4";
                        }
                        this.getTaskList();
                      });
                    }, onChanged: (value, _) {});
              },
              child: Container(
                margin: EdgeInsets.only(right: Styles.spacing16),
                alignment: Alignment.center,
                child: Text(this.selectStatus,
                    style: TextStyle(
                        fontSize: Styles.Middle16Font, color: Styles.WhiteGray,fontWeight: Styles.FontMainWeight)),
              ),
            )
          ]
      ),
      body: Container(
        color: Styles.MainBackgroundColor,
        padding:
            EdgeInsets.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
                child: NotificationListener(
              onNotification: (_) {
                FocusScope.of(context).requestFocus(new FocusNode());
                return false;
              },
              child: EasyRefresh.custom(
                  shrinkWrap: true,
                  firstRefresh: true,
                  controller: _controller,
                  header: MaterialHeader(),
                  footer: ClassicalFooter(
                      loadingText: '加载中',
                      loadText: '上拉加载',
                      noMoreText: '没有更多数据',
                      loadedText: '加载完成',
                      infoText: '更新于 %T',
                      textColor: Styles.NoMoreColor,
                      showInfo: false),
                  emptyWidget: (dataSource.length == 0 && !firstLoad)
                      ? Center(
                    child: Image(
                      image: AssetImage('assets/images/no_data.png'),
                      width: 128,
                      height: 150,
                    ),
                  )
                      : null,
                  onRefresh: () async {
                    _controller.finishLoad(success: true, noMore: false);
                    if (mounted) {
                      page = 1;
                      this.getTaskList();
                    }
                  },
                  onLoad: () async {
                    await Future.delayed(Duration(seconds: 2), () {
                      if (mounted) {
                        page++;
                        this.getTaskList();
                      }
                    });
                  },
                  slivers: <Widget>[
                    SliverList(
                      delegate: SliverChildBuilderDelegate(
                            (context, index) {
                          return GestureDetector(
                            onTap: () {
                              Get.toNamed(RouteConfig.problemComplete,
                                  arguments: {
                                    'businessId': this.dataSource[index]
                                    ['id'],
                                    'taskId': ''
                                  });
                            },
                            child: Container(
                              color: Colors.white,
                              padding: EdgeInsets.fromLTRB(
                                  Styles.spacing16,
                                  Styles.spacing8,
                                  Styles.spacing16,
                                  Styles.spacing8),
                              margin: EdgeInsets.fromLTRB(
                                  Styles.spacing8,
                                  Styles.spacing4,
                                  Styles.spacing8,
                                  Styles.spacing4),
                              child:  Row(
                                crossAxisAlignment:
                                CrossAxisAlignment.start,

                                children: [
                                  Expanded(
                                      child: Column(
                                        crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            child: Text(
                                              "检查人  ${this.dataSource[index]['checkStaff']}",
                                              style: TextStyle(
                                                  color: Styles.DetailColor,
                                                  fontSize: Styles.NormalFont),
                                            ),
                                          ),
                                          Container(
                                            child: Text(
                                              "检查日期  ${this.dataSource[index]['deadlineDateStr']}",
                                              style: TextStyle(
                                                  color: Styles.DetailColor,
                                                  fontSize: Styles.NormalFont),
                                            ),
                                          ),
                                          Container(
                                            child: Text(
                                              this.dataSource[index]['summary'],
                                              style: TextStyle(
                                                  color: Styles.LeftTitleColor,
                                                  fontSize: Styles.NormalFont13),
                                            ),
                                          )
                                        ],
                                      )),
                                 Column(
                                   crossAxisAlignment: CrossAxisAlignment.end,
                                   children: [
                                     Row(
                                       children: [
                                         Container(
                                           color: this.dataSource[index]['level']=='2'?Styles.OrangeColor:(this.dataSource[index]['level']=='1'?Styles.BlueColor:Styles.RedColor),
                                           margin: EdgeInsets.fromLTRB(
                                               Styles.spacing4,
                                               0,
                                               Styles.spacing4,
                                               0),
                                           padding: EdgeInsets.fromLTRB(
                                               Styles.spacing4,
                                               Styles.spacing4,
                                               Styles.spacing4,
                                               Styles.spacing4),
                                           child: Text(
                                             this.dataSource[index]['level']=='2'?'中等':(this.dataSource[index]['level']=='1'?'一般':'重要'),
                                             style: TextStyle(
                                                 color: Colors.white,
                                                 fontSize:
                                                 Styles.SmallFont),
                                           ),
                                         ),
                                         Container(
                                           color:this.dataSource[index]['issueStatus']=='2'?Styles.OrangeColor:(this.dataSource[index]['issueStatus']=='4'?Styles.HomeGreenCard:(this.dataSource[index]['issueStatus']=='3'?Styles.YellowColor:Styles.OrangeColor)) ,
                                           margin: EdgeInsets.fromLTRB(
                                               Styles.spacing4,
                                               0,
                                               Styles.spacing4,
                                               0),
                                           padding: EdgeInsets.fromLTRB(
                                               Styles.spacing4,
                                               Styles.spacing4,
                                               Styles.spacing4,
                                               Styles.spacing4),
                                           child: Text(
                                             this.dataSource[index]['issueStatus']=='2'?'待整改':(this.dataSource[index]['issueStatus']=='4'?'已完结':(this.dataSource[index]['issueStatus']=='3'?'待复查':'待整改')),
                                             style: TextStyle(
                                                 color: Colors.white,
                                                 fontSize:
                                                 Styles.SmallFont),
                                           ),
                                         )
                                       ],
                                     ),
                                     Container(
                                       margin: EdgeInsets.fromLTRB(
                                           Styles.spacing4,
                                           Styles.spacing8,
                                           Styles.spacing4,
                                           0),
                                       alignment:Alignment.centerLeft,
                                       child: Text(this.dataSource[index]['isRead']==1?'已读':'未读',style: TextStyle(
                                         color: this.dataSource[index]['isRead']==1?Styles.GrayButtonColor:Styles.RedColor,fontSize: Styles.NormalFont
                                       ),),
                                     )
                                   ],
                                 )
                                ],
                              ),
                            ),
                          );
                        },
                        childCount: dataSource.length,
                      ),
                    ),
                  ])
            ))
          ],
        ),
      ),
    );
  }
}
